package main

import (
	"World/conf"
	"World/db"
	"World/game"
	"World/redis"
	"World/rpc"
	"World/timmer"
	"flag"
	"math/rand"
	"os"
	"runtime/pprof"
	"time"

	"World/common/logger"
	nt "World/network"
	"World/utils"
)

func InitLogger(file string, lvl int) {
	logger.New(file, lvl, logger.Rotate{Size: logger.GB, Expired: time.Hour * 24 * 7, Interval: time.Hour * 24})
}

func main() {
	defer utils.PrintPanicStack()

	filename := flag.String("conf_path", "../conf/world.xml", "config file path")
	logpath := flag.String("logpath", "../log/", "log file path")
	cpuprofile := flag.String("cpuprofile", "", "write cpu profile to file")
	secs := flag.Int("exitsecs", 0, "how many secs to exit, defaut 0 to never exit")
	lvl := flag.Int("lvl", 6, "log level default -debug")
	flag.Parse()
	InitLogger(*logpath+"world.log", *lvl)

	if *cpuprofile != "" {
		f, err := os.Create(*cpuprofile)
		if err != nil {
			logger.Info("open cpu profile error %v:", err)
		} else {
			pprof.StartCPUProfile(f)
			defer pprof.StopCPUProfile()
		}
	}
	var ch chan int = make(chan int)
	go waitFor(ch, *secs)

	//init rand seed
	rand.Seed(time.Now().UTC().UnixNano())

	//init config
	err := conf.LoadConf(*filename)
	if err != nil {
		logger.Info("error load conf fail %v:", err)
		return
	}

	logger.Info("load config file %v: success!", *filename)

	/*err = conf.SetEncryptKey()
	if err != nil {
		logger.Info("error set SetEncryptKey fail %v:", err)
		return
	}*/

	//http服务 目前暂时不用
	go game.Run()

	game.Init()

	timmer.Init()

	err = redis.Init()
	if err != nil {
		logger.Error("init redis failed err=%v", err)
	}

	go nt.StartSocketServer()
	err = db.InitMysql()
	if err != nil {
		logger.Error("init mysql failed err=%v", err)
		return
	}

	go rpc.DoGRPC()

	select {
	case _ = <-ch:
		logger.Info("---I'm done----")
		break
	}

}

func waitFor(ch chan int, secs int) {
	if secs <= 0 {
		return
	}
	time.Sleep(time.Duration(secs) * time.Second)

	logger.Info("-------------ready to exit--------------------")
	ch <- 1
}
